<template>
    <div class="chart-container">
        <Select
            class="switch-select"
            v-if="hasSwitch"
            v-model="switchKey"
            @on-change="handleSwitch"
        >
            <Option
                v-for="item in switchDataMap"
                :key="item.label"
                :value="item.label"
                >{{ item.label }}</Option
            >
        </Select>
        <div class="chart" ref="chart" :style="chartStyle"></div>
    </div>
</template>

<script>
import * as Theme from "./theme/theme.js";
export default {
    props: ["chartStyle", "chartData", "switchDataMap", "theme"],
    data() {
        return {
            hasSwitch: false,
            switchKey: "",
            echart: null,
        };
    },
    created() {
        // console.log(Theme, this.theme);
        this.regisiteTheme();
    },
    watch: {
        chartData: {
            immediate: true,
            deep: true,
            handler(chartData) {
                if (!chartData.title) return;
                // console.log("渲染图表", chartData);
                this.renderChart(chartData);
            },
        },
        switchDataMap: {
            immediate: true,
            handler(switchDataMap) {
                if (!switchDataMap || !switchDataMap.length) return;
                this.hasSwitch = true;
                this.switchKey = switchDataMap[0].label;
            },
        },
    },
    methods: {
        renderChart(chartData) {
            this.$nextTick(() => {
                if (!this.echart) {
                    this.echart = Echarts.init(this.$refs.chart, "walden");
                }
                this.echart.setOption(chartData);
            });
        },
        handleSwitch(key) {
            console.log(key);
            this.switchDataMap.filter((item) => {
                if (item.label == key) {
                    console.log(item.chartData);
                    this.renderChart(item.chartData);
                }
            });
        },
        regisiteTheme() {
            Echarts.registerTheme(this.theme, Theme[this.theme]);
        },
    },
};
</script>

<style lang="scss" scoped>
.chart-container {
    // margin: 0 10px;
    width: 100%;
}
.chart {
    width: 100%;
    // min-width: 500px;
    height: 400px;
}
.switch-select {
    float: right;
    width: 60px;
    z-index: 999;
    position: relative;
    top: -1px;
}
</style>